package cc.yugu.yhdw.common.tool.netty;

import io.netty.buffer.ByteBuf;
import org.apache.commons.lang.builder.ReflectionToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;

import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

public abstract class TypeOperator {

    static final Charset CHARSET_UTF_8 = Charset.forName("UTF-8");

    public void writeString(ByteBuf buffer, String str) {
        if(str == null) {
            buffer.writeInt(-1);
        } else {
            byte[] buf = str.getBytes(CHARSET_UTF_8);
            buffer.writeInt(buf.length);
            buffer.writeBytes(buf);
        }
    }

    public String readString(ByteBuf buffer) {
        int length = buffer.readInt();
        if(length == -1) {
            return null;
        } else {
            byte[] buf = new byte[length];
            buffer.readBytes(buf);
            return new String(buf, CHARSET_UTF_8);
        }
    }

    public void writeStringList(ByteBuf buffer, List<String> list) {
        buffer.writeInt(list.size());
        for(String e : list) {
            writeString(buffer, e);
        }
    }

    public List<String> readStringList(ByteBuf buffer) {
        List<String> list = new ArrayList<String>();
        int len = buffer.readInt();
        for(int i = 0; i < len; i++) {
            list.add( readString(buffer) );
        }

        return list;
    }

    public void writeIntList(ByteBuf buffer, List<Integer> list) {
        buffer.writeInt(list.size());
        for(Integer e : list) {
            buffer.writeInt(e);
        }
    }

    public List<Integer> readIntList(ByteBuf buffer) {
        List<Integer> list = new ArrayList<Integer>();
        int len = buffer.readInt();
        for(int i = 0; i < len; i++) {
            list.add( buffer.readInt() );
        }

        return list;
    }

    public void writeFloatList(ByteBuf buffer, List<Float> list) {
        buffer.writeInt(list.size());
        for(Float e : list) {
            buffer.writeFloat(e);
        }
    }

    public List<Float> readFloatList(ByteBuf buffer) {
        List<Float> list = new ArrayList<Float>();
        int len = buffer.readInt();
        for(int i = 0; i < len; i++) {
            list.add( buffer.readFloat() );
        }

        return list;
    }

    @Override
    public String toString() {
        return ReflectionToStringBuilder.toString(this, ToStringStyle.MULTI_LINE_STYLE);
    }

}
